package com.sdkj.recruit.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.sdkj.recruit.model.ResultCode;
import com.sdkj.recruit.model.ResultData;
import com.sdkj.recruit.service.IWechatTokenService;
import com.sdkj.recruit.util.CheckoutUtil;
import com.sdkj.recruit.util.DateUtil;
import com.sdkj.recruit.util.WxSignatrueUtil;
import com.sdkj.recruit.wechat.AccessToken;
import com.sdkj.recruit.wechat.JsapiTicket;
import com.sdkj.recruit.wechat.WeChatProxy;
import com.sdkj.recruit.wechat.WechatPost;
import com.sdkj.recruit.wechat.WechatSign;
import com.sdkj.recruit.wechat.WechatToken;

import net.sf.json.JSONObject;

/**
 * 微信公众号验签服务
 * 
 * @author shenxiaozhong
 *
 */
@Controller
@Path("/signature")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class WechatSignatureController {

	
	@Autowired
	private IWechatTokenService tokenService;
	
	
	private static final Logger logger = Logger.getLogger(WechatSignatureController.class);

	
	/**
	 * token验证服务
	 * 
	 * @param request
	 * @param response
	 */
	@Path("/check")
	@GET
	public void check(@Context HttpServletRequest request, @Context HttpServletResponse response) {

		boolean isGet = request.getMethod().toLowerCase().equals("get");
		PrintWriter print;
		if (isGet) {
			// 微信加密签名
			String signature = request.getParameter("signature");
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			// 随机数
			String nonce = request.getParameter("nonce");
			// 随机字符串
			String echostr = request.getParameter("echostr");

			logger.info("signature：" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce);
			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
				logger.info("验证签名成功。。。");
				try {
					print = response.getWriter();
					print.write(echostr);
					print.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}

	/**
	 * 获取微信端签名
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@Path("/getSign")
	@GET
	public WechatSign getTickes(@Context HttpServletRequest request, @Context HttpServletResponse response) {

		String link = request.getParameter("link");
		String timestamp = request.getParameter("timestamp");
		String noncestr = request.getParameter("noncestr");
		ResultData<Object> result =getAccessToken(request, response);
		String access_token = JSONObject.fromObject(result.getObj()).getString("access_token");
		JsapiTicket ticket = WeChatProxy.getTicket(access_token);
		String sign = WxSignatrueUtil.getWxShareSignatrue(ticket.getTicket(), noncestr, link, timestamp);
		WechatSign config = new WechatSign();
		config.setAppId("wx21b0660087859fb2");
		config.setNonceStr(noncestr);
		config.setSignature(sign);
		config.setTimestamp(timestamp);
		return config;

	}
	
	/**
	 * 获取访问token
	 * @param request
	 * @param response
	 * @return
	 */
	@Path("/getAccessToken")
	@GET
	public ResultData<Object> getAccessToken(@Context HttpServletRequest request, @Context HttpServletResponse response) {

		
		// 判断token是否存在
		WechatToken localToken = tokenService.queryTokenByAppId("wx21b0660087859fb2");
		if (localToken == null) {
			AccessToken token = WeChatProxy.getAccessToken("client_credential", "wx21b0660087859fb2","4fcf526d00060ccd1320ba1493b7df83");
			logger.info("本地不存在token，调用微信服务获取token为："+token.getAccess_token());
			WechatToken wt =new WechatToken();
			wt.setAccess_token(token.getAccess_token());
			wt.setCreateToken(new Date());
			wt.setExpires_in(token.getExpires_in());
			wt.setAppId("wx21b0660087859fb2");
			tokenService.saveToken(wt);
			return ResultCode.success("获取token成功", token);
		} else {
			logger.info("本地存在token，直接获取本地，值为："+localToken.getAccess_token());
			// 判断本地是否过期
			Date currentDate=new Date();
			logger.info("当前时间:"+DateUtil.dataToString(currentDate, "yyyy-MM-dd HH:mm:ss"));
			Date createTokenDate =localToken.getCreateToken();
			Date addDate =new Date(createTokenDate.getTime()+localToken.getExpires_in()*1000);
			logger.info("过期时间:"+DateUtil.dataToString(addDate, "yyyy-MM-dd HH:mm:ss"));
			if(currentDate.getTime()>addDate.getTime()) {
				AccessToken token = WeChatProxy.getAccessToken("client_credential", "wx21b0660087859fb2","4fcf526d00060ccd1320ba1493b7df83");
				logger.info("本地存在token，过期，重新获取："+token.getAccess_token());
				// 更新token
				tokenService.updataToken("wx21b0660087859fb2",token,new Date());
				return ResultCode.success("获取token成功", token);
			}
			AccessToken token =new AccessToken();
			token.setAccess_token(localToken.getAccess_token());
			return ResultCode.success("获取token成功", token);
		}
	}
	
	/**
	 * 获取发票详情
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@Path("/getInvoiceInfo")
	@GET
	public ResultData<Object> getInvoiceInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) {

		String card_id = request.getParameter("card_id");
		String encrypt_code = request.getParameter("encrypt_code");

		logger.info("获取发票详情：card_id="+card_id);
		logger.info("获取发票详情：encrypt_code="+encrypt_code);
		
		ResultData<Object> result =getAccessToken(request, response);
		String access_token = JSONObject.fromObject(result.getObj()).getString("access_token");
		String url = "https://api.weixin.qq.com/card/invoice/reimburse/getinvoiceinfo?access_token=" + access_token;
		JSONObject param =new JSONObject();
		param.put("card_id", card_id);
		param.put("encrypt_code", encrypt_code);
		String onvoiceResult = WechatPost.post(url, param.toString());
		logger.info("获取发票详情返回结果:" + onvoiceResult);
		return ResultCode.success("获取发票详情返回结果", onvoiceResult);
	}
}
